import json
import requests


class DecisionClient:
    def __init__(self, endpoint='http://localhost:5000/decision'):
        self.endpoint = endpoint

    def make_decision_request(self, game_state):
        """发送决策请求并获取响应"""
        headers = {'Content-Type': 'application/json'}
        response = requests.post(
            self.endpoint,
            data=json.dumps(game_state, ensure_ascii=False).encode('utf-8'),
            headers=headers
        )
        return self._parse_response(response.json())

    def _parse_response(self, response_data):
        """解析决策响应"""
        if response_data.get('error'):
            raise DecisionError(response_data['error'])
        return {
            'strategy': response_data['strategy'],
            'actions': self._validate_actions(response_data['actions'])
        }

    def _validate_actions(self, actions):
        """校验动作合法性"""
        valid_actions = []
        for action in actions:
            if action['type'] not in ['select', 'replace', 'confirm']:
                continue
            valid_actions.append(action)
        return valid_actions